/*
  Copyright (c) 2012, Qusai Al Abdallah and Omar Fawzi 
 * All rights reserved.

  Redistribution and use in source and binary forms, with or without modification, 
  are permitted provided that the following conditions are met:

    - Redistributions of source code must retain the above copyright notice, this 
       list of conditions and the following disclaimer.
       
    - Redistributions in binary form must reproduce the above copyright notice, 
       this list of conditions and the following disclaimer in the documentation 
       and/or other materials provided with the distribution.
       

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
  SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
  OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 
  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
*/


package primerdb;

import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.*;
import java.awt.*;

import java.util.List;
import java.util.Vector;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.tree.*;

import java.io.*;
import javax.swing.filechooser.*;

import java.math.*;

import java.awt.event.ActionListener;

import javax.swing.text.DefaultEditorKit;

import java.util.StringTokenizer;



public class SearchFrame extends javax.swing.JFrame {

   private static int IDXFOLDERID = 3;
   private static int IDXPRIMERID = 0;
   
    /** Creates new form SearchFrame */
   public SearchFrame(PrimerDao db, PrimerDBUI gui) {
       this.db = db;
       this.gui = gui;
       
       
       
       initComponents();
       setResizable(false);
       tblSearchPrimers.setAutoCreateRowSorter(true);
       tblSearchPrimers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
       tblSearchPrimers.getSelectionModel().addListSelectionListener(new RowListener());
 
               
       header = new Vector<String>();
       header.add("ID");
       header.add("Primer Name");
       header.add("Ann Temp");
       header.add("Folder ID");
       header.add("Concentration");
       header.add("Target");
       header.add("Date");
       data = new Vector<Vector<String>>();
 
        
 //       populateTable();
   }
   
   
   private void refreshTable() {       
       
       data = db.searchPrimers(search);
       
       tblSearchPrimers.setModel(new NoEditDefaultTableModel(data, header));

       tblSearchPrimers.removeColumn(tblSearchPrimers.getColumnModel().getColumn(IDXFOLDERID));       
       tblSearchPrimers.removeColumn(tblSearchPrimers.getColumnModel().getColumn(IDXPRIMERID));

       
    }
   

   

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblSearchPrimers = new javax.swing.JTable();
        txtSearchPrimers = new javax.swing.JTextField();
        btnSearchPrimers = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Search for Primers");

        tblSearchPrimers.setFont(new java.awt.Font("Arial", 0, 12));
        tblSearchPrimers.setPreferredSize(null);
        tblSearchPrimers.setModel(new NoEditDefaultTableModel(data, header));
        jScrollPane1.setViewportView(tblSearchPrimers);

        txtSearchPrimers.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        txtSearchPrimers.setText("<Search for Primers>");

        btnSearchPrimers.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btnSearchPrimers.setText("Search");
        btnSearchPrimers.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchPrimersActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtSearchPrimers, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSearchPrimers, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(txtSearchPrimers))
                    .addComponent(btnSearchPrimers, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnSearchPrimersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchPrimersActionPerformed
   search = txtSearchPrimers.getText();
   refreshTable();
}//GEN-LAST:event_btnSearchPrimersActionPerformed


    
    
    /**
     * @param args the command line arguments
     */
//
//    public static void main(String args[]) {
//        /* Set the Nimbus look and fseel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                new SearchFrame().setVisible(true);
//            }
//        });
//    }

    
    
    

        
    int selectedPrimerIndex;
    int selectedPrimerID;
    int selectedFolderID;
    
    private class RowListener implements ListSelectionListener {
        public void valueChanged(ListSelectionEvent event) {
            if (event.getValueIsAdjusting()) {
                return;
            }
            selectedPrimerIndex = tblSearchPrimers.getSelectionModel().getLeadSelectionIndex();
            // The next line is for sorting -- the view index does not correspond to the model index
            // that's why we have this conversion
            selectedPrimerIndex = tblSearchPrimers.convertRowIndexToModel(selectedPrimerIndex);
            System.out.println("SearchFrame -- index of selected primer: " + selectedPrimerIndex);
            if(selectedPrimerIndex >= 0) {
               selectedPrimerID = Integer.parseInt(data.elementAt(selectedPrimerIndex).elementAt(IDXPRIMERID));
               selectedFolderID = Integer.parseInt(data.elementAt(selectedPrimerIndex).elementAt(IDXFOLDERID));
               System.out.println(selectedFolderID);
              
               // select the right folder
               
               gui.changeSelectionTree(selectedFolderID);
               
               // select the right primer
               gui.changeSelectionTable(selectedPrimerID);
               
            }
            else {              
/*               for (int i = 0; i < data.size(); i++) {
                  if(Integer.parseInt(data.elementAt(i).elementAt(IDXFOLDERID)) == selectedFolderID) {
                     selectedPrimerIndex = i;
                     System.out.println("index of new: " + selectedPrimerIndex);
                     tblSearchPrimers.changeSelection(i, 0, false, false);
                     break;
                  }
               }
               */
               
            }

        }
    }
    
    
   
   PrimerDao db;
   PrimerDBUI gui;
   private Vector<Vector<String>> data;
   private Vector<String> header;
   private String search = "";
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSearchPrimers;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblSearchPrimers;
    private javax.swing.JTextField txtSearchPrimers;
    // End of variables declaration//GEN-END:variables
}
